package com.zbf.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class VedioDataListener extends AnalysisEventListener<VedioData> {

    private OkHttpClient okHttpClient;

    private List<VedioData> list = new ArrayList<VedioData>();

    public List<VedioData> getList() {
        return list;
    }

    public void setList(List<VedioData> list) {
        this.list = list;
    }

    public VedioDataListener(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    public VedioDataListener() {
    }

    @Override
    public void invoke(VedioData vedioData, AnalysisContext analysisContext) {


        Response execute = null;
        try {
            if (!"".equals(vedioData.getVedioLink()) && vedioData.getVedioLink() != null && (vedioData.getVedioLink().startsWith("http") || vedioData.getVedioLink().startsWith("https"))) {
                Request request = new Request.Builder().url(vedioData.getVedioLink()).get().build();
                execute = okHttpClient.newCall(request).execute();
                String url = execute.request().url().url().toString();
                //https://www.douyin.com/video/7002517498608241957?previous_page=app_code_link
                String vedioId = url.split("\\?")[0].split("video/")[1];
                System.out.println(vedioId + "====>" + vedioId);
                vedioData.setVedioId(vedioId);
            }
            list.add(vedioData);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (execute != null) {
                execute.close();
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("解析完毕后");
    }
}
